package com.loukou.lkt.web.processor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.loukou.lkt.lkt.bo.AllocationOrderBo;
import com.loukou.lkt.lkt.bo.AllocationOrderDetailSubmitBo;
import com.loukou.lkt.lkt.bo.AllocationOrderSubmitBo;
import com.loukou.lkt.lkt.bo.GoodsBo;
import com.loukou.lkt.lkt.bo.PageList;
import com.loukou.lkt.lkt.entity.AllocationOrder;
import com.loukou.lkt.lkt.entity.AllocationOrderDetail;
import com.loukou.lkt.lkt.entity.Warehouse;
import com.loukou.lkt.lkt.enums.AllocationOrderStateEnum;
import com.loukou.lkt.lkt.enums.PositionTypeEnum;
import com.loukou.lkt.lkt.enums.WarehouseTypeEnum;
import com.loukou.lkt.lkt.resp.RespDto;
import com.loukou.lkt.lkt.service.AllocationOrderService;
import com.loukou.lkt.lkt.service.GoodsService;
import com.loukou.lkt.lkt.service.WarehouseService;
import com.loukou.lkt.lkt.utils.VoucherCodeUtil;
import com.mysql.jdbc.StringUtils;

//账号
@Service
public class AllocationOrderProcessor {
	@Autowired
	private AllocationOrderService allocationOrderService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private WarehouseService warehouseService;

	public RespDto<PageList<AllocationOrderBo>> getAllocationOrderlst(
			String orderCode,int orderState, int outWarehouseId,int inWarehouseId,List<Integer> myWarehouseIds,
			String outUserName,String startCreateTimeStr,String endCreateTimeStr,
			String startOutTimeStr,String endOutTimeStr,String startInTimeStr,String endInTimeStr,int pageIndex,int pageSize){
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startCreateTime = null;
		Date endCreateTime = null;
		
		Date startOutTime = null;
		Date endOutTime = null; 
		
		Date startInTime = null;
		Date endInTime = null;
		
	    try{if(!StringUtils.isNullOrEmpty(startCreateTimeStr))
	    {startCreateTime = sf.parse(startCreateTimeStr+" 00:00:00");}
	    }catch(Exception e){e.printStackTrace();}
	    try{if(!StringUtils.isNullOrEmpty(endCreateTimeStr)){
	    	endCreateTime = sf.parse(endCreateTimeStr+" 23:59:59");}
	    }catch(Exception e){e.printStackTrace();}
	    try{if(!StringUtils.isNullOrEmpty(startOutTimeStr)){
            	startOutTime = sf.parse(startOutTimeStr+" 00:00:00");}
	    }catch(Exception e){e.printStackTrace();}
	    try{if(!StringUtils.isNullOrEmpty(endOutTimeStr)){
	    		endOutTime = sf.parse(endOutTimeStr+" 23:59:59");}
	    }catch(Exception e){e.printStackTrace();}
	    try{if(!StringUtils.isNullOrEmpty(startInTimeStr)){
            	startInTime = sf.parse(startInTimeStr+" 00:00:00");}
	    }catch(Exception e){e.printStackTrace();}
	    try{if(!StringUtils.isNullOrEmpty(endInTimeStr)){
	    		endInTime = sf.parse(endInTimeStr+" 23:59:59");}
	    }catch(Exception e){e.printStackTrace();}
	    
		return allocationOrderService.getAllocationOrderlst(orderCode, orderState, outWarehouseId,
				inWarehouseId, myWarehouseIds, outUserName,
				startCreateTime, endCreateTime, startOutTime,
				endOutTime, startInTime, endInTime, pageIndex, pageSize);
	}
	//获取详细信息
	public List<AllocationOrderDetail> getDetails(int orderId){
		return allocationOrderService.getDetailsByOrderId(orderId);
	}
	
	@Transactional
	public RespDto<Object> save(AllocationOrderSubmitBo allocation){
		RespDto<Object> resp = new RespDto<Object>();
		if(allocation == null){
			resp.setCode(201);
			resp.setMsg("无数据");
			return resp;
		}
		if(allocation.getOutWarehouseId()<0){
			resp.setCode(202);
			resp.setMsg("请选择出库仓库");
			return resp;
		}
		if(allocation.getInWarehouseId()<0){
			resp.setCode(202);
			resp.setMsg("请选择入库仓库");
			return resp;
		}
		Warehouse warehouseout = warehouseService.getWarehouse(allocation.getOutWarehouseId());
		Warehouse warehousein = warehouseService.getWarehouse(allocation.getInWarehouseId());
		if(warehouseout == null || warehousein==null){
			resp.setCode(202);
			resp.setMsg("仓库数据已更新，请刷新页面");
			return resp;
		}
		if(warehouseout.getWarehouseType() != WarehouseTypeEnum.TYPE_WAREHOUSE.getType()){
			resp.setCode(202);
			resp.setMsg("只能从仓库类型为"+WarehouseTypeEnum.TYPE_WAREHOUSE.getComment()+"的仓库调出，请重新选则调出仓库");
			return resp;
		}
		if(warehousein.getWarehouseType() != WarehouseTypeEnum.TYPE_WAREHOUSE.getType()){
			resp.setCode(202);
			resp.setMsg("只能向仓库类型为"+WarehouseTypeEnum.TYPE_WAREHOUSE.getComment()+"的仓库调入，请重新选则调入仓库");
			return resp;
		}	
		AllocationOrder alloctionOrder = new AllocationOrder();
		int outWarehouseIdOld = -1;
		if(allocation.getId()>0){
			//修改
			alloctionOrder = allocationOrderService.getAllocationOrderById(allocation.getId());
			if(alloctionOrder == null){
				resp.setCode(204);
				resp.setMsg("无此调拨单");
				return resp;
			}
			outWarehouseIdOld = alloctionOrder.getOutWarehouseId();
		}else{
			alloctionOrder.setId(0);
			alloctionOrder.setOrderCode(getOrderCode());
			alloctionOrder.setOutUserId(allocation.getOutuserid());
			alloctionOrder.setOutUserName(allocation.getOutuserName());
		}
		alloctionOrder.setOutWarehouseId(allocation.getOutWarehouseId());
		alloctionOrder.setInWarehouseId(allocation.getInWarehouseId());
		alloctionOrder.setAllocationCost(allocation.getAllocationCost());
		Date date1 = null;
		Date date2 = null;
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{if(!StringUtils.isNullOrEmpty(allocation.getHopeInTime()))
	    {date1 = sf.parse(allocation.getHopeInTime()+" 00:00:00");}
	    }catch(Exception e){e.printStackTrace();}
	    try{if(!StringUtils.isNullOrEmpty(allocation.getHopeOutTime())){
	    	date2 = sf.parse(allocation.getHopeOutTime()+" 00:00:00");}
	    }catch(Exception e){e.printStackTrace();}
		alloctionOrder.setHopeInTime(date1);
		alloctionOrder.setHopeOutTime(date2);
		alloctionOrder.setRemark(allocation.getRemark());
		List<AllocationOrderDetail> details = Lists.newArrayList();
		boolean hasDetail = false;
		for(AllocationOrderDetailSubmitBo detailbo: allocation.getDetails()){
			if(!StringUtils.isNullOrEmpty(detailbo.getOutGoodsSku())){
				hasDetail = true;
				if(detailbo.getOutGoodsPacking()>1 && detailbo.getPlanQuantity() % detailbo.getOutGoodsPacking() != 0){
					resp.setCode(205);
					resp.setMsg("商品:["+detailbo.getOutGoodsName()+"]调拨数量必须是箱规的整数倍");
					return resp;
				}
				
				GoodsBo goodsBo = goodsService.getGoods(allocation.getOutWarehouseId(), PositionTypeEnum.TYPE_Normal.getId(), detailbo.getOutGoodsId());
				int oldPlanNum = 0;
				if(allocation.getId()>0){
					//修改
					AllocationOrderDetail oldDetail = allocationOrderService.getDetail(allocation.getId(), detailbo.getOutGoodsId());
					if(oldDetail!=null){
						oldPlanNum = oldDetail.getPlanQuantity();
					}
				}
				if((goodsBo.getCurUseStock()+oldPlanNum)<detailbo.getPlanQuantity()){
					resp.setCode(206);
					resp.setMsg("商品:["+detailbo.getOutGoodsName()+"]调拨数量不能大于可用数量:"+(goodsBo.getCurUseStock()+oldPlanNum)+",请重新选则该商品");
					return resp;
				}
				AllocationOrderDetail detail = new AllocationOrderDetail();
				BeanUtils.copyProperties(detailbo, detail);
				details.add(detail);
			}
		}
		if(!hasDetail){
			resp.setCode(203);
			resp.setMsg("无商品明细");
			return resp;
		}
		saveData(alloctionOrder, details,outWarehouseIdOld);
		return resp;
	}
	
	@Transactional
	private void saveData(AllocationOrder alloctionOrder,List<AllocationOrderDetail> details,int outWarehouseIdOld){
		allocationOrderService.saveAllocation(alloctionOrder, details,outWarehouseIdOld);
	}
	private String getOrderCode(){
		String orderCode = VoucherCodeUtil.getVoucherCode(VoucherCodeUtil.ALLOCATION_PRIFIX);
		AllocationOrder entity = allocationOrderService.getAllocationOrder(orderCode);
		if(entity != null){
			return getOrderCode();
		}
		return orderCode;
	}
	//更改调拨单状态
	public RespDto<Object> saveState(int orderId,int state){
		RespDto<Object> resp=new RespDto<Object>(); 
		if(state == 1){
			//审核
			resp = checkTypeCheck(orderId);
			if(resp.getCode()!=200){
				return resp;
			}
			List<Object> lst = (List<Object>)resp.getResult();
			allocationOrderService.checkAndUpdateState(orderId,(Integer)lst.get(0),(List<AllocationOrderDetail>)lst.get(1));
		}else if(state== 6){
			//取消
			allocationOrderService.updateState(orderId, AllocationOrderStateEnum.TYPE_Delete.getId());
		}else{
			resp.setCode(201);
			resp.setMsg("未知的操作");
		}
		return resp;
	}
	//判断调拨单能否被审核
	private RespDto<Object> checkTypeCheck(int orderId){
		RespDto<Object> resp = new RespDto<Object>();
		AllocationOrder order = allocationOrderService.getAllocationOrderById(orderId);
		if(order == null){
			resp.setCode(201);
			resp.setMsg("此调拨单不存在");
			return resp;
		}
		if(order.getOrderState()!=AllocationOrderStateEnum.TYPE_NnCheck.getId()){
			resp.setCode(202);
			resp.setMsg("此调拨单不是未审核状态，不能审核");
			return resp;
		}
		List<Object> lst = Lists.newArrayList();
		lst.add(order.getOutWarehouseId());
		List<AllocationOrderDetail> details = allocationOrderService.getDetailsByOrderId(orderId);
		String msg = "";
		for(AllocationOrderDetail detail : details){
			GoodsBo goodsBo = goodsService.getGoods(order.getOutWarehouseId(), PositionTypeEnum.TYPE_Normal.getId(), detail.getOutGoodsId());
			if(goodsBo.getCurUseStock()<detail.getPlanQuantity()){
				msg+="商品:["+detail.getOutGoodsName()+"]调拨数量不能大于可用数量:"+goodsBo.getCurUseStock()+",请重新编辑此商品的调拨数量,";
			}
		}
		if(!StringUtils.isNullOrEmpty(msg)){
			resp.setCode(206);
			resp.setMsg(msg);
			return resp;
		}
		lst.add(details);
		resp.setResult(lst);
		return resp;
	}
}
